
package net.swa.index.web.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
import net.swa.dewei.beans.entity.DingDanCard;
import net.swa.dewei.beans.entity.District;
import net.swa.dewei.beans.entity.LifeGoods;
import net.swa.dewei.beans.entity.MenDian;
import net.swa.dewei.beans.entity.WeixinAddress;
import net.swa.dewei.beans.entity.WeixinInfo;
import net.swa.dewei.beans.vo.CardCarItems;
import net.swa.dewei.beans.vo.VoListPage;
import net.swa.dewei.service.DingDanCardService;
import net.swa.dewei.service.LifeCardCarService;
import net.swa.dewei.service.LifeGoodsService;
import net.swa.dewei.service.MenDianService;
import net.swa.dewei.service.WeixinAddressService;
import net.swa.system.beans.entity.Dict;
import net.swa.system.service.ICommonService;
import net.swa.util.BuzConst;

/**
 * 得威生活  卡购流程
 * 
 * @author Administrator
 * 
 */
public class CardIndexAction extends AbstractBaseIndexAction
{
    private static final long serialVersionUID = 7868090805552756795L;

    private final Logger log = Logger.getLogger(CardIndexAction.class);

    /** 门店查询接口 */
    private MenDianService menDianService;

    /** 公用方法接口 */
    private ICommonService commonService;

    private LifeGoodsService lifeGoodsService;

    private WeixinAddressService weixinAddressService;
    
    private DingDanCardService dingDanCardService;

    /**一卡通商城购物车**/
    private LifeCardCarService lifeCardCarService;

    /**订单**/
    private DingDanCard model;

    /**得威生活商品详情**/
    private LifeGoods bean;

    /**各个阶段json**/
    private String json;

    /**商品列表专用json**/
    private String goodsJson;

    private Long id;

    private Double lat;

    private Double lng;

    /** 微信id */
    private String wxid;

    /** 公众号id **/
    private String gzhId;

    /** 安全令牌 */
    private String token;

    private String name;

    /**附近门店自取or 送货上门**/
    private String buyType;

    //购买产品的id和数量
    private Integer[] buyNums;

    //购买产品的id和数量
    private Long[] ids;

    private Long goodId;

    private Integer buyNum;

    /**省列表**/
    private List<District> provinceList;

    /**市列表*/
    private List<District> cityList;

    /**县区列表*/
    private List<District> areaList;

    private WeixinAddress wxaddress;

    //收件人姓名
    private String cname;

    //收件人手机号
    private String mobi;

    //省
    private String province;

    //市
    private String city;

    private String town;

    private String address;

    /**指定门店时候门店id**/
    private Long mendId;

    //一卡通卡号
    private String carNo;

    private String serverPrice;
    
    //订单状态
    private String state;

    /**
     * 1.跳转到移动设备浏览主页面
     * 入口
     * @return
     * @throws Exception
     */
    public String main() throws Exception
    {
        model = new DingDanCard();
        // List<LifeGoods> list = lifeGoodsService.queryList(name, BuzConst.STATUS_YES, BuzConst.MAXNUM);
        VoListPage<LifeGoods> vo = lifeGoodsService.queryVoList(name, BuzConst.STATUS_YES, BuzConst.MAXNUM);
        json = getJson(vo);
        if (!StringUtils.isBlank(wxid))
        {
            // 将wxid 保存到session
            setSessionAttribute("wxid", wxid);
            addCookie("wxid", wxid);
            if (null != lat && null != lng)
            {
                model.setLat(lat);
                model.setLng(lng);
            }
        }
        else
        {
            if (log.isDebugEnabled())
            {
                log.debug("没有获取wxid,访问附近门店。。");
            }
            return "main";
        }
        return "main";
    }

    /***
     * 条件搜索返回数据
     * @return
     * @throws Exception 
     */
    public String queryDatas() throws Exception
    {
        VoListPage<LifeGoods> vo = lifeGoodsService.queryVoList(name, BuzConst.STATUS_YES, BuzConst.MAXNUM);
        outJson(vo);
        return null;
    }

    /**
     * 1——a.滚动时候加载下一页（也可考虑将来做成整体刷新）
     * scroll  加载
     * @return
     * @throws Exception
     */
    public String queryMore() throws Exception
    {
        if (null != id && id > 0)
        {
            VoListPage<LifeGoods> map = lifeGoodsService.queryVoListByLastId(name, BuzConst.STATUS_YES, 10, id);
            outJson(map);
        }
        else
        {
            outError("没有数据");
        }
        return null;
    }

    /***
     * 2.单件商品查看
     * 可加入购物车 或者 直接购买
     * @return
     * @throws Exception
     */
    public String queryById() throws Exception
    {
        if (null != lat && null != lng)
        {
            log.debug("已经具备位置信息。。。。");
            log.debug("lat is " + lat);
            log.debug("lng is " + lng);
        }

        bean = lifeGoodsService.queryById(id);
        return "queryById";
    }

    /***
     * 3.单件直接购买，选择地址，
     * @return
     */
    public String queryAddress()
    {
        //服务费
        serverPrice = "10";
        String[] keys = { "title", "key" };
        Object[] values = new Object[] { BuzConst.CONFIG_INFO, BuzConst.CONFIG_CARD_SERVER_PRICE };
        List<Dict> dl = commonService.search(Dict.class, keys, values);
        if (null != dl && dl.size() > 0)
        {
            Dict di = dl.get(0);
            serverPrice = di.getValue();
        }
        setSessionAttribute(BuzConst.CARD_SERVER_PRICE, serverPrice);
        //
        List<WeixinAddress> address = null;
        if (null != ids && null != buyNums && ids.length > 0)
        {
            if (ids.length == buyNums.length)
            {
                wxid = (String) getSessionAttribute("wxid");
                if (!StringUtils.isBlank(wxid))
                {
                    //查询默认地址
                    address = weixinAddressService.queryListByWeixin(wxid);

                    if (null != address && address.size() > 0)
                    {
                        wxaddress = address.get(0);
                        for (WeixinAddress a : address)
                        {
                            if (a.isChecked())
                            {
                                wxaddress = a;
                                break;
                            }
                        }
                        List<LifeGoods> list = lifeGoodsService.queryBuyList(ids, buyNums);
                        goodsJson = getJson(list);
                        return "bindAddress";
                    }
                    else
                    {
                        return "address";
                    }
                }
                else
                {
                    log.debug("wxid is null ");
                }
            }
        }

        log.debug("在这里没有返回结果说明数据传输有问题，ids is " + ids);
        log.debug("，buyNums is " + buyNums + "wxid is " + wxid);
        return "error";
    }

    /**
     * 改变默认地址
     * @return
     */
    public String changeCheckedAddr()
    {        
        if (null != ids && null != buyNums && ids.length > 0 && null != id)
        {
            if (ids.length == buyNums.length)
            {
                wxid = (String) getSessionAttribute("wxid");
                wxaddress = weixinAddressService.updateReturnModel(wxid, id);
                if (null != wxaddress)
                {
                    List<LifeGoods> list = lifeGoodsService.queryBuyList(ids, buyNums);
                    goodsJson = getJson(list);
                    return "bindAddress";
                }
                else
                {
                    return "address";
                }
            }
        }

        log.debug("在这里没有返回结果说明数据传输有问题，ids is " + ids);
        log.debug("，buyNums is " + buyNums + "wxid is " + wxid);
        return "error";
    }

    //进入地址管理界面
    public String queryAddrManage()
    {
        //  provinceList = commonService.search("pid", "0", District.class);
        wxid = (String) getSessionAttribute("wxid");
        List<WeixinAddress> address = weixinAddressService.queryListByWeixin(wxid);
        if (null != address && address.size() > 0)
        {
            json = getJson(address);
            return "address";
        }
        return "editAddress";
    }

    public String editReceiptAddr() throws Exception
    {
        provinceList = commonService.search("pid", "0", District.class);
        if (id == null)
        {
            wxaddress = new WeixinAddress();
        }
        else
        {
            wxaddress = commonService.commonFind(WeixinAddress.class, id);
            cityList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { wxaddress.getProvince(), 2 });
            areaList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { wxaddress.getCity(), 3 });
        }
        return "editAddress";
    }

    //保存微信用户地址
    public String saveAddr() throws Exception
    {
        if (null != ids && null != buyNums && ids.length > 0)
        {
            if (ids.length == buyNums.length)
            {
                wxid = (String) getSessionAttribute("wxid");
                if (null != wxaddress)
                {
                    wxaddress.setWxid(wxid);
                    wxaddress = weixinAddressService.saveReturnModel(wxid, wxaddress);
                    if (null != wxaddress)
                    {
                        List<LifeGoods> list = lifeGoodsService.queryBuyList(ids, buyNums);
                        goodsJson = getJson(list);
                        return "bindAddress";
                    }
                    else
                    {
                        log.debug("保存地址失败1");
                    }
                }
                else
                {
                    log.debug("保存地址失败2");
                }
            }
            else
            {
                log.debug("没有要购买的商品信息ids与buyNums数量不一致");
            }
        }
        else
        {
            log.debug("没有要购买的商品信息");
        }
        queryAddrManage();
        return null;
    }

    /**
     * 3.根据传入的经纬度，取方圆指定范围的店面
     * 
     * @throws Exception
     */
    public String queryNearMend() throws Exception
    {
        if (null != lat && null != lng)
        {
            List<MenDian> list = menDianService.queryMendianNearByLatLng(lat, lng, null, true, true, null, 20);
            json = getJson(list);
        }
        return "queryNearMend";
    }

    /**
     * 直接保存“送货上门订单”
     * @return
     */
    public String saveDingdanDirect()
    {
        if (null != ids && null != buyNums && ids.length > 0 && null != id)
        {
            wxid = (String) getSessionAttribute("wxid");
            //商品、商品数量、送货地址不为空时候下单
            if (ids.length == buyNums.length && (!StringUtils.isBlank(wxid)))
            {

                DingDanCard d = new DingDanCard();
                //先整理订单基本数据
                d.setMendianId(null);
                d.setCarNo(carNo);
                String[] keys = { "title", "key" };
                Object[] values = new Object[] { BuzConst.CONFIG_INFO, BuzConst.CONFIG_CARD_SERVER_PRICE };
                List<Dict> dl = commonService.search(Dict.class, keys, values);
                if (null != dl && dl.size() > 0)
                {
                    Dict di = dl.get(0);
                    Double dv = Double.parseDouble(di.getValue());
                    if (null == dv)
                    {
                        dv = 10d;
                    }
                    d.setServicePrice(dv);
                }
                else
                {
                    d.setServicePrice(10d);
                }

                d.setUserId(wxid);
                wxaddress = weixinAddressService.queryById(id);
                if (null != wxaddress)
                {
                    d.setAddressId(id);
                    d.setProvince(wxaddress.getProvince());
                    d.setCity(wxaddress.getCity());
                    d.setTown(wxaddress.getTown());
                    d.setAddress(wxaddress.getAddress());
                    d.setKehuName(wxaddress.getCname());
                    d.setLxTel(wxaddress.getMobi());
                }
                d.setLat(lat);
                d.setLng(lng);

                model = lifeGoodsService.saveDingdanModel(d, ids, buyNums, BuzConst.CARD_BUYTYPE_SM);

                json = getJson(model);
                return "dingdan";
            }
        }
        return "error";
    }

    /**
     * 选择门店后下订单
     * @return
     */
    public String saveDingdanMend()
    {
        if (null != ids && null != buyNums && ids.length > 0 && (null != id) && (null != mendId))
        {
            wxid = (String) getSessionAttribute("wxid");
            //商品、商品数量、送货地址不为空时候下单
            if (ids.length == buyNums.length && (!StringUtils.isBlank(wxid)))
            {

                DingDanCard d = new DingDanCard();
                //先整理订单基本数据
                d.setMendianId(mendId);
                d.setUserId(wxid);
                d.setServicePrice(0);
                d.setCarNo(carNo);
                wxaddress = weixinAddressService.queryById(id);
                if (null != wxaddress)
                {
                    d.setAddressId(id);
                    d.setProvince(wxaddress.getProvince());
                    d.setCity(wxaddress.getCity());
                    d.setTown(wxaddress.getTown());
                    d.setAddress(wxaddress.getAddress());
                    d.setKehuName(wxaddress.getCname());
                    d.setLxTel(wxaddress.getMobi());
                }
                d.setLat(lat);
                d.setLng(lng);
                model = lifeGoodsService.saveDingdanModel(d, ids, buyNums, BuzConst.CARD_BUYTYPE_MD);
                json = getJson(model);
                return "dingdan";
            }
        }
        return "error";
    }

    /**
     * 添加商品到购物车
     * wxid 必须在session中
     * @return
     * @throws Exception 
     */
    public String addToCar() throws Exception
    {
        wxid = (String) getSessionAttribute("wxid");
        if (null != goodId && null != buyNum)
        {
            Map<String, Object> map = lifeCardCarService.addToCar(goodId, buyNum, wxid);
            if (null != map)
            {
                outJson(map);
            }
            else
            {
                outError("添加失败！");
            }
        }
        else
        {
            outError("传值出错！");
        }
        return null;
    }

    /**
     * 改变购物车某商品数量
     * @return
     * @throws Exception 
     */
    public String changeCount() throws Exception
    {
        boolean f = lifeCardCarService.updateBuyNum(buyNum, id);
        if (f)
        {
            outSuccess();
        }
        else
        {
            outError("更改数量失败");
        }
        return null;
    }

    /***
     * 移除购物车某一项
     * @return
     * @throws Exception 
     */
    public String removeItem() throws Exception
    {
        boolean f = lifeCardCarService.deleteItem(id);
        if (f)
        {
            outSuccess();
        }
        else
        {
            outError("更改数量失败");
        }
        return null;
    }

    /**
     * 查看我的购物车信息
     * 可以选择购物车中的商品进行支付
     * @return
     */
    public String queryMyCar()
    {
        wxid = (String) getSessionAttribute("wxid");
        CardCarItems its = lifeCardCarService.queryItems(wxid);
        json = getJson(its);
        return "myCar";
    }

    /**
     * 用户中心界面
     * 将提供查看订单界面？
     * @return
     */
    public String userInfo()
    {

        return "userinfo";
    }

    /**
     * 进入地址管理界面
     * 该页面仅仅对用户地址做管理
     * @return
     */
    public String queryUserAddr()
    {
        wxid = (String) getSessionAttribute("wxid");
        List<WeixinAddress> address = weixinAddressService.queryListByWeixin(wxid);
        if (null != address && address.size() > 0)
        {
            json = getJson(address);
            return "useraddress";
        }
        return "addUserAddress";
    }

    /***
     * 用户管理里面新增or编辑地址
     * @return
     * @throws Exception
     */
    public String editUserAddr() throws Exception
    {
        provinceList = commonService.search("pid", "0", District.class);
        if (id == null)
        {
            wxaddress = new WeixinAddress();
        }
        else
        {
            wxaddress = commonService.commonFind(WeixinAddress.class, id);
            cityList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { wxaddress.getProvince(), 2 });
            areaList = commonService.search(District.class, new String[] { "pname", "level" }, new Object[] { wxaddress.getCity(), 3 });
        }
        return "addUserAddress";
    }

    public String saveUserAddr()
    {
        List<WeixinAddress> address = new ArrayList<WeixinAddress>();
        wxid = (String) getSessionAttribute("wxid");
        if (null != wxaddress)
        {
            wxaddress.setWxid(wxid);
            address = weixinAddressService.saveReturnList(wxid, wxaddress);
        }
        json = getJson(address);
        return "useraddress";
    }

    public String saveDefaultAddr()
    {
        wxid = (String) getSessionAttribute("wxid");
        if (null != id)
        {
            List<WeixinAddress> address = weixinAddressService.saveDefault(id, wxid);
            if (null != address && address.size() > 0)
            {
                json = getJson(address);
                return "useraddress";
            }
        }
        return "addUserAddress";
    }
    
    /**查询订单**/
    public String queryOrder()
    {
        int num=3;//异步加载数据
        id=null;
        VoListPage<DingDanCard> dingdans=null;
        if (StringUtils.isBlank(wxid))
        {
            wxid = (String) getSessionAttribute("wxid");
            if (StringUtils.isBlank(wxid))
            {
                return "error";
            }
        }else
        {
            setSessionAttribute("wxid", wxid);
        }
        //查询用户，判断其是否门店用户
        WeixinInfo info = commonService.findByAttribute(WeixinInfo.class, "openid", wxid);
        if(null!=info&&info.isMendian()){
            String[] ss = { "wxid", "status" };
            Object[] vv = { wxid, 1 };
            List<MenDian> mlist = commonService.search(MenDian.class, ss, vv);
            if (null != mlist && mlist.size() > 0)
            {
                // 是门店用户
                MenDian m = commonService.search(MenDian.class, ss, vv).get(0);
                if (null != m)
                {
                    dingdans = dingDanCardService.queryMendDingdans(m.getId(),id,num);
                    json=getJson(dingdans);
                    return "mendOrders";
                }
            }
        }
        dingdans=dingDanCardService.queryMyDingdans(wxid,id,num);
        json=getJson(dingdans);
        return "myOrders";
    }
    
    /**查询订单数据
     * @throws Exception **/
    public String queryOrderDatas() throws Exception
    {
        int num=2;//异步加载数据
        VoListPage<DingDanCard> dingdans=null;
        if (StringUtils.isBlank(wxid))
        {
            wxid = (String) getSessionAttribute("wxid");
            if (StringUtils.isBlank(wxid))
            {
                outError("请重新进入");
            }
        }else
        {
            setSessionAttribute("wxid", wxid);
        }
        //查询用户，判断其是否门店用户
        WeixinInfo info = commonService.findByAttribute(WeixinInfo.class, "openid", wxid);
        if(null!=info&&info.isMendian()){
            String[] ss = { "wxid", "status" };
            Object[] vv = { wxid, 1 };
            List<MenDian> mlist = commonService.search(MenDian.class, ss, vv);
            if (null != mlist && mlist.size() > 0)
            {
                // 是门店用户
                MenDian m = commonService.search(MenDian.class, ss, vv).get(0);
                if (null != m)
                {
                    dingdans = dingDanCardService.queryMendDingdans(m.getId(),id,num);
                    System.out.println("IIIIIIIIIIIIIII:   "+id);
                    outJson(dingdans);
                    return null;
                    
                }
            }
        }
          dingdans=dingDanCardService.queryMyDingdans(wxid,id,num);
//        VoListPage<DingDanCard> vo=new VoListPage<DingDanCard>();
//        if(null!=dingdans||dingdans.size()>0){
//            int lastIndex=dingdans.size()-1;
//            vo.setResult(dingdans);
//            if(num==dingdans.size()){
//               vo.setHasNext(true);
//            }
//            vo.setSuccess(true);
//            Long currentId=dingdans.get(lastIndex).getId();
//            vo.setCurrentId(currentId);
//        }
        outJson(dingdans);
        return null;
    }
    
    public String  processOrder() throws Exception{
        
        if(null!=id&&(!StringUtils.isBlank(state))){
            Long[] ids = new Long[1];
            ids[0] = id;
            dingDanCardService.batchUpdateState(ids, state);
            outSuccess();
        }else{
            outError("传参出错");
        }
            
        return null;
    }
    
    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }
    
    public Double getLat()
    {
        return lat;
    }

    public void setLat(Double lat)
    {
        this.lat = lat;
    }

    public Double getLng()
    {
        return lng;
    }

    public void setLng(Double lng)
    {
        this.lng = lng;
    }

    public String getWxid()
    {
        return wxid;
    }

    public void setWxid(String wxid)
    {
        this.wxid = wxid;
    }

    public String getGzhId()
    {
        return gzhId;
    }

    public void setGzhId(String gzhId)
    {
        this.gzhId = gzhId;
    }

    public String getToken()
    {
        return token;
    }

    public void setToken(String token)
    {
        this.token = token;
    }

    public String getJson()
    {
        return json;
    }

    public void setJson(String json)
    {
        this.json = json;
    }

    public DingDanCard getModel()
    {
        return model;
    }

    public void setModel(DingDanCard model)
    {
        this.model = model;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public LifeGoods getBean()
    {
        return bean;
    }

    public void setBean(LifeGoods bean)
    {
        this.bean = bean;
    }

    public String getBuyType()
    {
        return buyType;
    }

    public void setBuyType(String buyType)
    {
        this.buyType = buyType;
    }

    public Integer[] getBuyNums()
    {
        return buyNums;
    }

    public void setBuyNums(Integer[] buyNums)
    {
        this.buyNums = buyNums;
    }

    public Long[] getIds()
    {
        return ids;
    }

    public void setIds(Long[] ids)
    {
        this.ids = ids;
    }

    public String getGoodsJson()
    {
        return goodsJson;
    }

    public void setGoodsJson(String goodsJson)
    {
        this.goodsJson = goodsJson;
    }

    public List<District> getProvinceList()
    {
        return provinceList;
    }

    public void setProvinceList(List<District> provinceList)
    {
        this.provinceList = provinceList;
    }

    public List<District> getCityList()
    {
        return cityList;
    }

    public void setCityList(List<District> cityList)
    {
        this.cityList = cityList;
    }

    public List<District> getAreaList()
    {
        return areaList;
    }

    public void setAreaList(List<District> areaList)
    {
        this.areaList = areaList;
    }

    public String getCname()
    {
        return cname;
    }

    public void setCname(String cname)
    {
        this.cname = cname;
    }

    public String getMobi()
    {
        return mobi;
    }

    public void setMobi(String mobi)
    {
        this.mobi = mobi;
    }

    public String getProvince()
    {
        return province;
    }

    public void setProvince(String province)
    {
        this.province = province;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public String getTown()
    {
        return town;
    }

    public void setTown(String town)
    {
        this.town = town;
    }

    public String getAddress()
    {
        return address;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    public WeixinAddress getWxaddress()
    {
        return wxaddress;
    }

    public void setWxaddress(WeixinAddress wxaddress)
    {
        this.wxaddress = wxaddress;
    }

    public Long getMendId()
    {
        return mendId;
    }

    public void setMendId(Long mendId)
    {
        this.mendId = mendId;
    }

    public Long getGoodId()
    {
        return goodId;
    }

    public void setGoodId(Long goodId)
    {
        this.goodId = goodId;
    }

    public Integer getBuyNum()
    {
        return buyNum;
    }

    public void setBuyNum(Integer buyNum)
    {
        this.buyNum = buyNum;
    }

    public String getCarNo()
    {
        return carNo;
    }

    public void setCarNo(String carNo)
    {
        this.carNo = carNo;
    }

    
    public String getServerPrice()
    {
        return serverPrice;
    }

    public void setServerPrice(String serverPrice)
    {
        this.serverPrice = serverPrice;
    }
    
    public String getState()
    {
        return state;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    @Required
    @Resource
    public void setCommonService(ICommonService commonService)
    {
        this.commonService = commonService;
    }

    @Required
    @Resource
    public void setLifeCardCarService(LifeCardCarService lifeCardCarService)
    {
        this.lifeCardCarService = lifeCardCarService;
    }
    
    @Required
    @Resource
    public void setLifeGoodsService(LifeGoodsService lifeGoodsService)
    {
        this.lifeGoodsService = lifeGoodsService;
    }

    @Required
    @Resource
    public void setWeixinAddressService(WeixinAddressService weixinAddressService)
    {
        this.weixinAddressService = weixinAddressService;
    }
    
    @Required
    @Resource
    public void setMenDianService(MenDianService menDianService)
    {
        this.menDianService = menDianService;
    }

    @Required
    @Resource
    public void setDingDanCardService(DingDanCardService dingDanCardService)
    {
        this.dingDanCardService = dingDanCardService;
    }
}
